package com.apkcore.core.notification

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import com.apkcore.core.cp.ApkcoreContentProvider

class ForegroundNotification(
    private val context: Context, private val channelId: String, private val
    smallIcon: Int
) {

    private val notificationManager: NotificationManager by lazy {
        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    }

    init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "Foreground Notification Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun showNotification(notificationId: Int, title: String, message: String, intent: Intent) {
        val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        val notificationBuilder = NotificationCompat.Builder(context, channelId)
            .setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(smallIcon)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)

        notificationManager.notify(notificationId, notificationBuilder.build())
    }

    fun cancelNotification(notificationId: Int) {
        notificationManager.cancel(notificationId)
    }

    companion object {
        fun openNotification(
            title: String,
            message: String,
            channelId: String,
            cls: Class<*>,
            notificationId: Int = 1,
            smallIcon: Int = android.R.drawable.ic_dialog_info,
        ): ForegroundNotification {
            val notificationIntent = Intent(ApkcoreContentProvider.appContext, cls)
            val notification = ForegroundNotification(ApkcoreContentProvider.appContext, channelId, smallIcon)
            notification.showNotification(notificationId, title, message, notificationIntent)
            return notification
        }
    }
}